package cn.gcjxsc.service.merchant;

import cn.gcjxsc.entity.merchant.Merchant;
import cn.gcjxsc.entity.merchant.MerchantAccount;
import cn.gcjxsc.repository.merchant.MerchantAccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * @author pumbaa
 * @since 1.0
 */
@Service
public class MerchantAccountService {
    @Autowired
    private MerchantAccountRepository accountRepository;

    public List<MerchantAccount> findByMerchantId(Merchant merchant){
        return accountRepository.findByMerchantId(merchant.getId());
    }

    public MerchantAccount findByMerchantIdAndType(Merchant merchant, Integer type) {
        MerchantAccount account = accountRepository.findByMerchantIdAndType(merchant.getId(), type);
        if (null == account) {
            account = new MerchantAccount();
            account.setMerchant(merchant);
            account.setType(type);
            account.setAmount(BigDecimal.ZERO);
        }
        return account;
    }

    /**
     * 保存或更新账户信息
     * @param accounts 商户账户信息
     * @return
     */
    @Transactional
    public List<MerchantAccount> saveOrUpdate(MerchantAccount... accounts) {
        List<MerchantAccount> merchantAccounts = Arrays.asList(accounts);
        return accountRepository.save(merchantAccounts);
    }
}
